﻿using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using PMS.BLL;
using PMS.Entity;
using PMS.Resources;
using PMS.Win;
using PMS.Utils;
using DevExpress.XtraEditors.Mask;
using PMS.DanhMucChung;
using System.Collections.Generic;
using PMS.ValidationRules;
using PMS.ReportViewer;


namespace PMS.ChucNang
{
    public partial class GiaoHangEntry : FormEntryBase
    {
        #region Constants
        private const string BINDING_PROPERTY = "EditValue";
        private string NEW_String = Messages.GetString(Constants.NEW);
        #endregion

        #region Private Members
        protected PhieuGiaoHangBO m_Service;
        #endregion

        #region Properties
        protected Entity.PhieuGiaoHang CurrentGiaoHangEntry
        {
            get
            {
                return base.Entity as Entity.PhieuGiaoHang;
            }
            set
            {
                base.Entity = value;
            }
        }
        #endregion

        #region Services
        public PhieuGiaoHangBO Service
        {
            get
            {
                if (m_Service == null)
                {
                    m_Service = new PhieuGiaoHangBO();
                }
                return m_Service;
            }
        }
        #endregion

        #region Constructors
        public GiaoHangEntry(string functionID)
            : base(functionID)
        {
            InitializeComponent();
            Init();
        }
        #endregion

        #region Init Data and Style
        private void Init()
        {
            InitData();
            InitStyle();
        }

        private void InitData()
        {
        }

        private void InitStyle()
        {
            bteSoPG.Tag = "Ignore";
            bteMaKH.BackColor = REQUIRED_FIELD_COLOR;
            dteNgayGiao.BackColor = REQUIRED_FIELD_COLOR;
            bteSoPX.BackColor = REQUIRED_FIELD_COLOR;
            txtSoHD.BackColor = REQUIRED_FIELD_COLOR;

            this.bteSoPG.Properties.MaxLength = 14;
            this.txtSoHD.Properties.MaxLength = 12;
            this.bteSoPX.Properties.MaxLength = 14;
            this.txtPhuongThucGiao.Properties.MaxLength = 35;
            this.txtNguoiGiao.Properties.MaxLength = 35;
            this.txtNguoiNhan.Properties.MaxLength = 35;
            this.bteMaKH.Properties.MaxLength = 6;
            this.txtPhuongThucTT.Properties.MaxLength = 35;
            this.txtGhiChu.Properties.MaxLength = 200;
        }
        #endregion

        #region override methods

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            if (this.CurrentGiaoHangEntry == null)
            {
                this.DoNew();
            }
        }

        protected override void BindingToControls(IBaseEntity entity)
        {
            base.BindingToControls(entity);

            this.bteSoPG.DataBindings.Clear();
            this.txtSoHD.DataBindings.Clear();
            this.bteSoPX.DataBindings.Clear();
            this.txtPhuongThucGiao.DataBindings.Clear();
            this.txtNguoiGiao.DataBindings.Clear();
            this.txtNguoiNhan.DataBindings.Clear();
            this.bteMaKH.DataBindings.Clear();
            this.txtPhuongThucTT.DataBindings.Clear();
            this.txtGhiChu.DataBindings.Clear();

            this.bteSoPG.DataBindings.Add(BINDING_PROPERTY, entity, PhieuGiaoHangColumns.SoPG.ToString());
            this.txtSoHD.DataBindings.Add(BINDING_PROPERTY, entity, PhieuGiaoHangColumns.SoHD.ToString());
            this.bteSoPX.DataBindings.Add(BINDING_PROPERTY, entity, PhieuGiaoHangColumns.SoPX.ToString());
            this.txtPhuongThucGiao.DataBindings.Add(BINDING_PROPERTY, entity, PhieuGiaoHangColumns.PhuongThucGiao.ToString());
            this.txtNguoiGiao.DataBindings.Add(BINDING_PROPERTY, entity, PhieuGiaoHangColumns.NguoiGiao.ToString());
            this.txtNguoiNhan.DataBindings.Add(BINDING_PROPERTY, entity, PhieuGiaoHangColumns.NguoiNhan.ToString());
            this.bteMaKH.DataBindings.Add(BINDING_PROPERTY, entity, PhieuGiaoHangColumns.MaKH.ToString());
            this.txtPhuongThucTT.DataBindings.Add(BINDING_PROPERTY, entity, PhieuGiaoHangColumns.PhuongThucTT.ToString());
            this.txtGhiChu.DataBindings.Add(BINDING_PROPERTY, entity, PhieuGiaoHangColumns.GhiChu.ToString());

            PhieuGiaoHang pg = entity as PhieuGiaoHang;
            if (pg.SoPG == NEW_String)
            {
                CanPrint = false;
            }
            else
            {
                CanPrint = true;
            }

            dteNgayGiao.DateTime = (DateTime)CurrentGiaoHangEntry.NgayGiao;
        }

        protected override void FocusFirtsControl()
        {
            base.FocusFirtsControl();
            this.txtSoHD.Focus();
        }

        protected override void InitValidationRules()
        {
            base.InitValidationRules();
            Validator validate = new Validator(ValidationProvider);
            validate.AddValidationRule(base.CreateNotEmptyValidationRule());
            SetValidator(validate, dteNgayGiao);

            validate = new Validator(ValidationProvider);
            validate.AddValidationRule(new CustomerValidationRules(null, true));
            SetValidator(validate, bteMaKH);

            validate = new Validator(ValidationProvider);
            validate.AddValidationRule(new PhieuXuatValidateRule(null,true));
            SetValidator(validate, bteSoPX);
        }

        public override void New()
        {
            this.CurrentGiaoHangEntry = new Entity.PhieuGiaoHang { 
            NgayGiao = Constants.BUSINESS_DATE,
            SoPG = NEW_String
            };
            base.New();
        }

        public override void IsNewChanged()
        {
            if (IsNew)
            {
                bteSoPX.Enabled = true;
                bteMaKH.Enabled = true;
                txtSoHD.Enabled = true;
                dteNgayGiao.Enabled = true;
            }
            else
            {
                bteSoPX.Enabled = false;
                bteMaKH.Enabled = false;
                txtSoHD.Enabled = false;
                dteNgayGiao.Enabled = false;
            }
        }

        protected override bool Save()
        {
            try
            {
                if (IsNew)
                {
                    CurrentGiaoHangEntry = Service.CreatePhieuGiaoHang(CurrentGiaoHangEntry);
                }
                else
                {
                    Service.UpdatePhieuGiaoHang(CurrentGiaoHangEntry);
                }
                return true;
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }
        }

        protected override bool Delete()
        {
            try
            {
                Service.DeletePhieuGiaoHang(CurrentGiaoHangEntry);
                return true;
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }
        }

        protected override void Print()
        {
            try
            {
                PhieuGiaoHangViewer pg = new PhieuGiaoHangViewer(CurrentGiaoHangEntry.SoPG);
                pg.WindowState = FormWindowState.Maximized;
                pg.StartPosition = FormStartPosition.CenterParent;
                pg.ShowDialog();
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        public override void Cancel()
        {
            //your code here
            base.Cancel();
        }

        protected override IBaseEntity GetEntity()
        {
            //need to get the latest record of the current Entity's ID or code then return it
            return base.GetEntity();
        }
        #endregion

        private void bteSoPG_Click(object sender, EventArgs e)
        {
            try
            {
                var form = new PhieuGiaoLookup();
                if (form.ShowDialog() == DialogResult.OK)
                {
                    IsNew = false;
                    if (form.PhieuGiaoHangSelected != null)
                    {
                        LoadObjectOnForm(bteSoPG.Text.Trim(), form.PhieuGiaoHangSelected.SoPG, form.PhieuGiaoHangSelected);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void bteSoPG_Enter(object sender, EventArgs e)
        {
            if (bteSoPG.Text.Equals(NEW_String))
            {
                bteSoPG.Text = string.Empty;
            }
        }

        private void bteSoPG_Leave(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(bteSoPG.Text)&&!IsNew)
                {
                    New();
                }
                else
                {
                    if (CurrentGiaoHangEntry == null) return;
                    string previousCode = DataConvertUltils.ToString(CurrentGiaoHangEntry.SoPG);
                    string code = DataConvertUltils.ToString(bteSoPG.EditValue);
                    if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
                    {
                        PhieuGiaoHang temPhieuXuat = Service.GetPhieuGiaoHangByID(code);
                        LoadObjectOnForm(previousCode, code, temPhieuXuat);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void bteSoPX_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                XuatKhoLookup form = new XuatKhoLookup(false);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    if (form.PhieuXuatSelected != null)
                    {
                        CurrentGiaoHangEntry.SoPX = form.PhieuXuatSelected.SoPX;
                        CurrentGiaoHangEntry.SoHD = form.PhieuXuatSelected.SoHD;
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void bteSoPX_Leave(object sender, EventArgs e)
        {
            try
            {
                string code = DataConvertUltils.ToString(bteSoPX.EditValue);
                if(!string.IsNullOrEmpty(code))
                {
                    PhieuXuat px = (new PhieuXuatBO()).GetPhieuXuatByID(code);
                    if (px != null)
                    {
                        CurrentGiaoHangEntry.SoPX = px.SoPX;
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void bteMaKH_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                CustomerLookup form = new CustomerLookup();
                if (form.ShowDialog() == DialogResult.OK)
                {
                    if (form.CustomerSelected != null)
                    {
                        CurrentGiaoHangEntry.MaKH = form.CustomerSelected.MaKH;
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void bteMaKH_Leave(object sender, EventArgs e)
        {
            try
            {
                string code = DataConvertUltils.ToString(bteMaKH.EditValue);
                if (!string.IsNullOrEmpty(code))
                {
                    KhachHang kh = (new KhachHangBO()).GetKhachHangByID(code);
                    if (kh != null)
                    {
                        CurrentGiaoHangEntry.MaKH = kh.MaKH;
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        #region Lookups
        #endregion

        #region Form's function
        private void LoadObjectOnForm(string previousCode, string code, IBaseEntity ObjectLoad)
        {
            if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
            {
                if (IsNew)
                {
                    if (ObjectLoad != null)
                    {
                        if (IsDataChanged)
                        {
                            var result = ShowSaveConfimMessage();
                            if (result == DialogResult.Yes)
                            {
                                CurrentGiaoHangEntry.SoPG = previousCode;
                                if (!base.ValidateControls() || !Save())
                                {
                                    return;
                                }
                            }
                        }
                        Entity = ObjectLoad;
                        IsNew = false;
                        IsDataChanged = false;
                    }
                    else
                    {
                        CurrentGiaoHangEntry.SoPG = code;
                        Entity = CurrentGiaoHangEntry;
                        IsNew = true;//important
                        IsDataChanged = true;//important                        
                    }
                }
                else
                {
                    if (!IsDataChanged)
                    {
                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentGiaoHangEntry = new PhieuGiaoHang();
                            CurrentGiaoHangEntry.SoPG = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentGiaoHangEntry;
                            IsNew = true;//important
                            IsDataChanged = true;//important   
                        }
                    }
                    else
                    {
                        var result = ShowSaveConfimMessage();
                        if (result == DialogResult.Yes)
                        {
                            CurrentGiaoHangEntry.SoPG = previousCode;
                            if (!base.ValidateControls() || !Save())
                            {
                                return;
                            }
                        }

                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentGiaoHangEntry = new PhieuGiaoHang();
                            CurrentGiaoHangEntry.SoPG = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentGiaoHangEntry; ;
                            IsNew = true;//important
                            IsDataChanged = true;//important 
                        }
                    }
                }
                ClearErrorMessage();
            }
        }
        #endregion

        private void dteNgayGiao_Leave(object sender, EventArgs e)
        {
            if (dteNgayGiao.IsModified)
            {
                CurrentGiaoHangEntry.NgayGiao = dteNgayGiao.DateTime;
            }
        }
    }
}
